package com.example.demo.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.example.demo.aliyunmessage.entity.Message;

import java.util.Random;

public class SendMessageUtil {
    static final String PRODUCT = "Dysmsapi";
    static final String DOMAIN = "dysmsapi.aliyuncs.com";
    static final String ACCESS_KEY_ID = "LTAI5tBEngLjNSmWSF78iUiR";
    static final String ACCESS_KEY_SECRET = "h42MOG5H3Fcpgs2keI6fDE4Ll1Z17z";


    public static SendSmsResponse sendSms(Message message) throws ClientException {
//        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
//        IAcsClient client = new DefaultAcsClient(profile);
//
//        CommonRequest request = new CommonRequest();
//        request.setSysMethod(MethodType.POST);
//        request.setSysDomain("dysmsapi.aliyuncs.com");
//        request.setSysVersion("2017-05-25");
//        request.setSysAction("SendSms");
//        request.putQueryParameter("RegionId", "cn-hangzhou");
//        try {
//            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }


        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(message.getMobile());
        request.setSignName(message.getSignName());
        request.setTemplateCode(message.getTemplateCode());
        request.setTemplateParam(message.getTemplateParam());
        SendSmsResponse sendSmsResponse = (SendSmsResponse) acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }

    public static String getSixNum() {
        String str = "0123456789";
        StringBuilder sb = new StringBuilder(4);

        for (int i = 0; i < 6; ++i) {
            char ch = str.charAt((new Random()).nextInt(str.length()));
            sb.append(ch);
        }

        return sb.toString();
    }


}